package com.atguigu.daijia.customer.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import com.atguigu.daijia.common.execption.GuiguException;
import com.atguigu.daijia.common.result.ResultCodeEnum;
import com.atguigu.daijia.customer.mapper.CustomerInfoMapper;
import com.atguigu.daijia.customer.mapper.CustomerLoginLogMapper;
import com.atguigu.daijia.customer.service.CustomerInfoService;
import com.atguigu.daijia.model.entity.customer.CustomerInfo;
import com.atguigu.daijia.model.entity.customer.CustomerLoginLog;
import com.atguigu.daijia.model.form.customer.UpdateWxPhoneForm;
import com.atguigu.daijia.model.vo.customer.CustomerLoginVo;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class CustomerInfoServiceImpl extends ServiceImpl<CustomerInfoMapper, CustomerInfo> implements CustomerInfoService {

    @Resource
    private WxMaService wxMaService;

    @Resource
    private CustomerLoginLogMapper customerLoginLogMapper;

    /**
     * 小程序登录
     * @param code
     * @return
     */
    @Override
    public Long login(String code) throws WxErrorException {
        /**1.通过code值，使用微信工具包对象去获取微信唯一标识openid**/
        WxMaJscode2SessionResult sessionInfo = wxMaService
                .getUserService()
                .getSessionInfo(code);
        String openid = sessionInfo.getOpenid();

        /**2. 根据openid 查询数据库，判断是否是第一次登录*/
        CustomerInfo customerInfo = super.getOne(Wrappers
                .<CustomerInfo>lambdaQuery()
                .eq(CustomerInfo::getWxOpenId, openid));

        /**3. 如果第一次登录，则添加信息到用户表中*/
        if (customerInfo == null) {
            customerInfo = new CustomerInfo();
            customerInfo.setNickname(String.valueOf(System.currentTimeMillis()));
            customerInfo.setAvatarUrl("https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg");
            customerInfo.setWxOpenId(openid);
            super.save(customerInfo);
        }
        /**4. 记录登录日志信息*/
        CustomerLoginLog customerLoginLog = new CustomerLoginLog();
        customerLoginLog.setCustomerId(customerInfo.getId());
        customerLoginLog.setMsg("小程序登录");
        customerLoginLogMapper.insert(customerLoginLog);

        return customerInfo.getId();
    }

    /**
     * 获取用户登录信息接口
     * @param customerId
     * @return
     */
    @Override
    public CustomerLoginVo getCustomerInfo(Long customerId) {
        CustomerInfo customerInfo = super.getById(customerId);

        // 返回vo
        if (customerInfo != null) {
            CustomerLoginVo customerLoginVo = new CustomerLoginVo();
            BeanUtils.copyProperties(customerInfo, customerLoginVo);
            customerLoginVo.setIsBindPhone(StringUtils.hasText(customerInfo.getPhone()));
            return customerLoginVo;
        }
        return null;
    }

    /**
     * 更新客户微信手机号
     * @param form
     * @return
     */
    @Override
    public Boolean updateWxPhoneNumber(UpdateWxPhoneForm form) {
        try {
            WxMaPhoneNumberInfo phoneNoInfo = wxMaService.getUserService().getPhoneNoInfo(form.getCode());
            String phoneNumber = phoneNoInfo.getPhoneNumber();

            CustomerInfo customerInfo = super.getById(form.getCustomerId());
            customerInfo.setPhone(phoneNumber);
            return super.updateById(customerInfo);
        } catch (WxErrorException e) {
            throw new GuiguException(ResultCodeEnum.DATA_ERROR);
        }
    }
}
